<template>
  <div id="index-page">
    <a-auto-complete
      style="width: 60vw"
      v-model:value="keyword"
      class="global-search"
      option-label-prop="title"
      :options="suggestions"
      @change="onKeywordChange"
      @select="onSelectSuggestion"
    >
      <a-input-search
        size="large"
        placeholder="搜索关键词"
        enter-button="搜索"
        @search="onSearch"
      />
    </a-auto-complete>
    <a-tabs
      @change="onTabChange"
      size="large"
      style="width: 80vw; margin-top: 20px"
      v-model:activeKey="type"
    >
      <a-tab-pane key="article" tab="文章">
        <ArticleList :article-list="articleList" />
      </a-tab-pane>
      <a-tab-pane key="picture" tab="图片">
        <PictureList :picture-list="pictureList" />
      </a-tab-pane>
      <a-tab-pane key="user" tab="用户">
        <UserList :user-list="userList" />
      </a-tab-pane>
    </a-tabs>
  </div>
</template>

<script setup lang="ts">
import myAxios from "../plugins/myAxios";
import ArticleList from "../components/ArticleList.vue";
import PictureList from "../components/PictureList.vue";
import UserList from "../components/UserList.vue";
import { ref, watchEffect } from "vue";
import { useRoute, useRouter } from "vue-router";
import debounce from "lodash.debounce";

const router = useRouter();
const route = useRoute();

const keyword = ref(route.query.keyword || "");
const type = ref(route.params.type || "article");

const articleList = ref([]);
const pictureList = ref([]);
const userList = ref([]);
const suggestions = ref([]);

const initSearchParams = {
  type: type.value,
  keyword: keyword.value,
};
const searchParams = ref(initSearchParams);

// 防抖函数，减少请求频率
const fetchSuggestions = debounce(async (value: string) => {
  if (value) {
    try {
      const res: any = await myAxios.post("search/suggest", { keyword: value });
      // 组件 options 格式：[{ value: string }]
      suggestions.value = res.map((item: any) => ({
        value: item,
      }));
    } catch (error) {
      console.error("Failed to fetch suggestions", error);
    }
  } else {
    suggestions.value = [];
  }
}, 1000);

const onSearch = (value: string) => {
  keyword.value = value;
  router.push({
    path: `/${type.value}`,
    query: { keyword: value },
  });
};

const onTabChange = (key: string) => {
  router.push({
    path: `/${key}`,
    query: { keyword: keyword.value },
  });
};

const onKeywordChange = (value: string) => {
  keyword.value = value;
  fetchSuggestions(value);
};

const onSelectSuggestion = (value: string) => {
  keyword.value = value;
  onSearch(value);
};

const loadData = async (params: any) => {
  const { type } = params;
  const query = { ...params, keyword: params.keyword };
  const res: any = await myAxios.post("search/all", query);
  if (type === "article") {
    articleList.value = res.dataList;
  } else if (type === "picture") {
    pictureList.value = res.dataList;
  } else if (type === "user") {
    userList.value = res.dataList;
  }
};

// 监听【回调函数中】访问的【响应式变量】，当这些变量发生变化时，自动执行回调函数
// => 监听 route.query.keyword、route.params.type
watchEffect(() => {
  searchParams.value = {
    ...initSearchParams,
    keyword: route.query.keyword,
    type: route.params.type || "article",
  } as any;

  keyword.value = route.query.keyword || "";
  type.value = route.params.type || "article";

  loadData(searchParams.value);
});
</script>

<style scoped>
#index-page {
  padding: 40px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
</style>
